<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .Div {
            width: 600px;
            height: 700px;
            border: 1px solid black;

        }

        .div1 {
            width: 600px;
            height: 500px;
        }

        p {
            margin-left: 20px;
        }

        .sp1,
        .sp2 {
            display: inline-block;
            width: 100px;
            height: 40px;
            line-height: 40px;
            margin: 30px 0 0 30px;
            text-align: center;
            border: 1px solid red;
            border-radius: 4px;
            font-weight: bold;
            cursor: pointer;
        }
    </style>
    <script src="./jq.js"></script>
</head>


<body>
    <div class="Div">
        <div class="div1"></div>
        <div><span class="sp1">+加入购物车</span>
            <span class="sp2"><a href="./购物车.html">查看购物车</a></span>

        </div>
    </div>

    <script src="./JQ源码.js"></script>
    <script>
        $(function () {
            //当前商品的id
            var goodsId = '';
            //商品名称
            var goodsName = '';
            window.onload = function () {
                // console.log(location.href);
                //
                goodsId = location.search.substr(4);
                getGoods();
            }
            function getGoods() {
                $.each(list, function (i, item) {
                    if (goodsId == item.id) {
                        renderById(item);
                        // console.log(item);
                        goodsName = item.name;
                    }

                })
            }
            // 根据id显示页面内容
            function renderById(date) {
                console.log(date);
                var str = '';
                var img = date.image;
                str = `<img width='300' height='300' src=${img} />
                    <h2>${date.name}</h2>
                    <p>单价：￥${date.price} 元/根</p>
                    <p>品牌： ${date.brandName} </p>
                    <p>库存:  ${date.stock}</p>
                   `;
                $('.div1').html(str);
            }
            //加入购物车，将数据存到本地
            $('.sp1').click(function () {
                //保证类型是数组，可以是空数组但不能是null
                var cartList = JSON.parse(localStorage.getItem('cartList')) || [];

                // console.log(goodsId);
                cartList.push(goodsId);
                console.log(cartList);
                //正常情况下，当iD重复时应使数量加一，而不是重复记录id。这个是后台的工作
                localStorage.setItem('cartList', JSON.stringify(cartList));
                alert(goodsName + '添加成功')
            })
        })
    </script>
</body>

</html>